package Server;




import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import Library.Books2;
import Library.Report;

import ocsf.server.*;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 *
 */
public class EchoServer extends AbstractServer implements Runnable 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;
  public static Connection conn;
  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port,String user,String pass) 
  {
	  super(port);
	  
System.out.println(user+" "+pass);
	    try {
			//conn = DriverManager.getConnection("jdbc:mysql://localhost/libary","root","root");
	    	conn = DriverManager.getConnection("jdbc:mysql://localhost/libary",user,pass);
	    	//conn = DriverManager.getConnection("jdbc:mysql://localhost/libary","root","");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
   */
  public void handleMessageFromClient
    (Object msg, ConnectionToClient client)
  {
	  
	  System.out.println(msg.getClass());
	    if(msg instanceof Books2)
	    {
	    	Books2 bk2=(Books2)msg;
	    	
	    	 if(!DBmethods.bookExists((bk2.getBookId())))//if book doesnt exists in catalog - add it
			  {
				  if(DBmethods.addBook(bk2))
				  {
					  try {
						  
						  client.sendToClient("Book number "+bk2.getBookId()+" was added successfully to catalog");
					  } catch (IOException e) {
						  // TODO Auto-generated catch block
						  e.printStackTrace();
					  }
				  }
				  else
				  {
					try {
						client.sendToClient("Book number "+bk2.getBookId()+" was not added successfully to catalog.\nTry again");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				  }
			  }
			  else
			  {
				  try {
					  client.sendToClient("Book number "+bk2.getBookId()+" already exists in catalog");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			  }
		  			  
	    }
	    
	    else if(msg instanceof Report)
	    {
	    	Report r=(Report)msg;
	    	try {
				client.sendToClient(DBmethods.addReport(r));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    
	    
	    
	    else{
	 
	    	String message[]=(String [])msg;
	    	System.out.println(message[0]);
	    	
	    	
	    	/****************************************************************************/
	    	
	   	 if (message[0].equals("login"))
		   {
				try {
					client.sendToClient(DBmethods.CheckLogIn(message[1],message[2]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }

		if (message[0].equals("logout"))
		   {
			try {
				client.sendToClient(DBmethods.changeStatus(message[1],0));
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }
		if (message[0].equals("msgOnExtendedBooks"))
		   {
				try {
					client.sendToClient(DBmethods.getMsgsOnExtendedBooks());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }
		
		if (message[0].equals("getWorkers"))
		   {
				try {
					client.sendToClient(DBmethods.getWorkersData());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }
		
		
		
		
		if(message[0].equals("get content"))
		{
			try {
				client.sendToClient(DBmethods.getcontent(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		 
		if(message[0].equals("getWorkerData"))
		{
			 try {
					client.sendToClient(DBmethods.getWorkerData(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		 if(message[0].equals("edit reader card"))
		 {
			 try {
			 if(DBmethods.editCard(message[1],message[2],message[3],message[4],message[5],message[6],message[7]))
							
				 {
				 client.sendToClient("Card edited successful");
				 }
			
			else
			 client.sendToClient("not successful to edit card");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
		 }
		 if(message[0].equals("getBooks"))
		 {
			 try {
				client.sendToClient(DBmethods.getBooks());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("get readers"))
		 {
			 try {
				client.sendToClient(DBmethods.getReaders());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 	
		 if(message[0].equals("getuserName"))
		 {
			 try {
				client.sendToClient(DBmethods.getuserName(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("getCopies"))
		 {
			 try {
				client.sendToClient(DBmethods.getCopies());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 if(message[0].equals("get reader card details"))
		 {
			 try {
				client.sendToClient(DBmethods.getReaderCardDetails(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		 }
		 
		 /*if(message[0].equals("getReaderCards"))
		 {
			 try {
				client.sendToClient(DBmethods.getReaderCards());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }*/
		 
		 if(message[0].equals("countByReaderCardStatus"))
		 {
			 try {
				client.sendToClient(DBmethods.countByReaderCardStatus());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("return copy"))
		 {
			 try {
				client.sendToClient(DBmethods.returnCopy(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 if(message[0].equals("countByLoanedCopies"))
		 {
			 try {
				client.sendToClient(DBmethods.countByLoanedCopies(message[1],message[2]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("getReports"))
		 {
			 try {
				client.sendToClient(DBmethods.getReports());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("getReport"))
		 {
			 try {
				client.sendToClient(DBmethods.getReport(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("countLateInReturns"))
		 {
			 try {
				client.sendToClient(DBmethods.countLateInReturns(message[1],message[2]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("avgForNumberOfLatesReport"))
		 {
			 try {
				client.sendToClient(DBmethods.avgForNumberOfLatesAndDurationReport());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("freezeCard"))
		 {
			 try {
				if(DBmethods.changeReaderCardStatus(Integer.parseInt(message[1]),"frozen"))
					client.sendToClient("Reader card number "+message[1]+" is now frozen");
				else client.sendToClient("Freezing reader card number "+message[1]+" was not executed\nTry again");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("checkForLoanedBooks"))
		 {
			 try {
				client.sendToClient(DBmethods.checkForLoanedBooks(message[1]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if(message[0].equals("changeReaderCardStatus"))
		 {
			 boolean res=DBmethods.changeReaderCardStatus(Integer.parseInt(message[1]),message[2]);
			 try {
				if(res)
					client.sendToClient("Status of reader card number "+message[1]+" is now "+message[2]);
				else client.sendToClient("Changing reader card number "+message[1]+" status was not executed\nTry again");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 if (message[0].equals("CheckReaderCardStudent"))
		   {
				try {
					client.sendToClient(DBmethods.CheckReaderCardStudent(message[1]));

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }
		 if (message[0].equals("search"))
		   {
				try {
					client.sendToClient(DBmethods.SearchBooks(message[1],message[2]));

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }
			
		      // return;
		   

		 if(message[0].equals("get copies in loan"))
		 {
			 try {
				client.sendToClient(DBmethods.getCopiesInLoan());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		 }
		 if (message[0].equals("loans student"))
		   {
				try {
					client.sendToClient(DBmethods.LendingHistory(message[1],message[2]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		   }
		   if (message[0].equals("Order book"))
		   {
				try {
					client.sendToClient(DBmethods.OrderBook(message[1]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		   }
		   if (message[0].equals("checkOrderBook"))
		   {
				try {
					System.out.println(message[1]+" "+message[2]);
					client.sendToClient(DBmethods.CheckOrderBook(message[1],message[2]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		   }
		   if (message[0].equals("LateReturn"))
		   {
				try {
					client.sendToClient(DBmethods.LateReturn(message[1]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		   }
		   
		   if (message[0].equals("getListOrderBook"))
		   {
				try {
					client.sendToClient(DBmethods.getListOrderBookStudent(message[1]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		   }
		   if (message[0].equals("StatisticInfoReport"))
		   {
				try {
					client.sendToClient(DBmethods.StatisticInfoReport());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		   }
		   
		
		 if (message[0].equals("Reader card"))
		   {
				try {
					client.sendToClient(DBmethods.getReaderCardStudent(message[1]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		   }
		 if (message[0].equals("editPersonalDetails"))
				   {
				try {        

							client.sendToClient(DBmethods.editPersonalDetails(message[1],message[2],message[3],message[4],message[5]));
							 

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				   }
		 
		   
		   if(message[0].equals("manual extend Books"))
		   {
			  
				try {
					client.sendToClient(DBmethods.extendManual(message[1],message[2],message[3]));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					
		   }			
			
		   if(message[0].equals("new loan"))
		   {
			   try {
				   client.sendToClient(DBmethods.newLoan(message[1],message[2],message[3]));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		   }
		   
		/*   if(message[0].equals("forgot"))
		    {
			   String s=DBmethods.forgot(message[1]);
			   try {
				client.sendToClient(s);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		   }*/
		  
			   if(message[0].equals("deleteBook"))
			   {
				   int id=Integer.parseInt(message[1]);
				   if(DBmethods.bookExists(id))
				   {
					   String s=DBmethods.deleteBook(id);
					   try {
						client.sendToClient(s);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					  
				  }
				  /*else
				  {
					  try {
						  client.sendToClient("Copy number "+message[1]+" already exists in catalog");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				  }
				   } */
				   else
				   {
					try {
						client.sendToClient("Book number "+id+" does not exists in catalog");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				   }
			   }
			   
			   if(message[0].equals("new reader card"))
			   {
				   try {
					client.sendToClient(DBmethods.newReaderCard(message[1],message[2],message[3],message[4],message[5]));
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				   
			   }
			   
			   if(message[0].equals("addCopy"))
			   {
				   int cId=Integer.parseInt(message[1]);
				   int bId=Integer.parseInt(message[2]);
				   if(DBmethods.bookExists(bId))
				   {
					  if(!DBmethods.copyExists(cId))//if copy doesnt exists in catalog - add it
					  {
						  DBmethods.addCopy(cId,bId);
						  try {
							client.sendToClient("Copy number "+message[1]+" of book number "+bId+" was added successfully to catalog");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						  
					  }
					  else
					  {
						  try {
							  client.sendToClient("Copy number "+message[1]+" of book number "+bId+" already exists in catalog");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					  }
				   }
				   else
				   {
						  try {
							  client.sendToClient("Book number "+bId+" does not exists in catalog");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				   }
			   }
				  
			   
				  if(message[0].equals("loans of user"))
				  {
					 try {
						client.sendToClient(DBmethods.extendLoan(message[1]));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				  }
				  
					
					 if (message[0].equals("lateReport"))
					   {
							try {
								client.sendToClient(DBmethods.lateReport());
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					   }


					 if (message[0].equals("lateReportBook"))
					   {
							try {
								client.sendToClient(DBmethods.lateReportBook(message[1]));
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					   }
				 
				  if(message[0].equals("getReaderId"))
				  {
					  try {
						client.sendToClient(DBmethods.getReaderId(message[1]));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				  }
			   
			   if(message[0].equals("deleteCopy"))
				   {
					   int cId=Integer.parseInt(message[1]);
					   int bId=DBmethods.matchCidToBid(cId);
					   if(!DBmethods.isLoaned(cId))
					   {
						   if((DBmethods.bookExists(bId)))
						   {
							   if(DBmethods.copyExists(cId))
							   {
								   DBmethods.deleteCopy(cId,bId);
								   try {
									client.sendToClient("Copy number "+cId+" of book number "+bId+" was removed successfully from catalog");
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							   }
						   
							   else
							   {
									try {
										client.sendToClient("Copy number "+cId+" of book number "+bId+" does not exists in catalog");
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							   }
						   }
						   else
						   {
								  try {
									  client.sendToClient("Book number "+bId+" does not exists in catalog");
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
						   }
					   }
					   else
					   {
						   
						  try {
							  client.sendToClient("Copy number "+cId+" is currently loaned, therefore it can not be removed from catalog");
						  } catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
							}
					   }
				   }
	    }
	    
	  }

    
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println
      ("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println
      ("Server has stopped listening for connections.");
  }
  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */

 
}
  

//End of EchoServer class
